package com.dacd.sdl.sendclient.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dacd.sdl.sendclient.EventBean.NoticeEvent;
import com.dacd.sdl.sendclient.EventBean.StopEvent;
import com.dacd.sdl.sendclient.R;
import com.dacd.sdl.sendclient.activity.Base.BaseActivity;
import com.dacd.sdl.sendclient.service.SdlService;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * Created by soule on 2018/2/26.
 * 输入IP地址进行连接的界面
 */

public class InputAddressActivity extends BaseActivity {

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            connectBtn.setEnabled(true);
            Toast.makeText(InputAddressActivity.this, (String) msg.obj, Toast.LENGTH_LONG).show();
        }
    };

    private final static String DEFAULT_IP = "192.168.1.4";
    private EditText inputIpEt;//输入IP的文本框
    private Button connectBtn;//连接按钮
    private Button disconnectBtn;//断开连接的按钮

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_input_address);
        inputIpEt = (EditText) findViewById(R.id.aia_ip_input_et);
        inputIpEt.setText(DEFAULT_IP);
        connectBtn = (Button) findViewById(R.id.aia_connect_btn);
        disconnectBtn = (Button) findViewById(R.id.aia_disconnect_btn);
        connectBtn.setOnClickListener(new View.OnClickListener() {//点击传入需要连接的ip地址
            @Override
            public void onClick(View v) {
                connectBtn.setEnabled(false);
                Intent proxyIntent = new Intent(InputAddressActivity.this, SdlService.class);
                proxyIntent.putExtra("ipAddress", inputIpEt.getText().toString());
                startService(proxyIntent);
            }
        });
        disconnectBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                connectBtn.setEnabled(true);
                EventBus.getDefault().post(new StopEvent());
            }
        });
    }

    /**
     * 接收到显示通知的事件
     *
     * @param noticeEvent
     */
    @Subscribe
    public void onEventMainThread(NoticeEvent noticeEvent) {
        if (noticeEvent != null) {
            Message msg = handler.obtainMessage();
            msg.obj = noticeEvent.getNoticeContent();
            handler.sendMessage(msg);
        }
    }
}
